package com.minyifang.wcspf.work.ui.user.activities;

import android.content.Intent;
import android.graphics.Color;
import android.graphics.Paint;
import android.os.Handler;
import android.support.annotation.NonNull;
import android.support.v4.content.ContextCompat;
import android.support.v7.widget.DividerItemDecoration;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.EditText;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.TextView;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.minyifang.wcspf.R;
import com.minyifang.wcspf.common.base.BaseMvpActivity;
import com.minyifang.wcspf.common.md5.SafeUtils;
import com.minyifang.wcspf.common.utils.AnimUtils;
import com.minyifang.wcspf.common.utils.ImageUtils;
import com.minyifang.wcspf.common.utils.LogUtil;
import com.minyifang.wcspf.common.utils.ToastHelper;
import com.minyifang.wcspf.work.event.RefreshEvent;
import com.minyifang.wcspf.work.model.HttpRespond;
import com.minyifang.wcspf.work.ui.Global;
import com.minyifang.wcspf.work.ui.goods.activities.GoodsDetailsActivity;
import com.minyifang.wcspf.work.ui.goods.activities.ShoppingCartActivity;
import com.minyifang.wcspf.work.ui.home.model.AddToCarBean;
import com.minyifang.wcspf.work.ui.home.model.ShoppingCarBean;
import com.minyifang.wcspf.work.ui.user.model.CollectionBean;
import com.minyifang.wcspf.work.ui.user.presenter.MyCollectionPresenter;
import com.minyifang.wcspf.work.ui.user.view.MyCollectionView;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.yanzhenjie.recyclerview.swipe.SwipeMenu;
import com.yanzhenjie.recyclerview.swipe.SwipeMenuBridge;
import com.yanzhenjie.recyclerview.swipe.SwipeMenuCreator;
import com.yanzhenjie.recyclerview.swipe.SwipeMenuItem;
import com.yanzhenjie.recyclerview.swipe.SwipeMenuItemClickListener;
import com.yanzhenjie.recyclerview.swipe.SwipeMenuRecyclerView;

import org.greenrobot.eventbus.EventBus;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

import static com.minyifang.wcspf.work.MyApplication.getContext;

/**
 * 我的收藏
 */
public class MyCollectionActivity extends BaseMvpActivity<MyCollectionView, MyCollectionPresenter> implements MyCollectionView, SwipeMenuCreator, SwipeMenuItemClickListener {


    @BindView(R.id.refreshLayout)
    SmartRefreshLayout mRefreshLayout;

    @BindView(R.id.recyclerView)
    SwipeMenuRecyclerView mSwipeMenuRecyclerView;

    private List<CollectionBean> mList;
    private CollectionAdapter mAdapter;

    private int pageIndex = 0;


    @BindView(R.id.iv_endView)
    ImageView mEndView;
    @BindView(R.id.tv_num)
    TextView tv_num;
    private ImageView mClickItemView;
    private AnimUtils mAnimUtils;
    private boolean mShowAnim;
    private LinearLayoutManager mLayoutManager;

    @Override
    protected int setContentLayoutRes() {
        return R.layout.activity_my_collection;
    }

    @Override
    protected void initView() {
        mAnimUtils = new AnimUtils(this);
        mList = new ArrayList<>();
        mAdapter = new CollectionAdapter();
        mSwipeMenuRecyclerView.setSwipeMenuCreator(this);
        mSwipeMenuRecyclerView.setSwipeMenuItemClickListener(this);
        mLayoutManager = new LinearLayoutManager(getContext());
        mSwipeMenuRecyclerView.setLayoutManager(mLayoutManager);
        DividerItemDecoration itemDecoration = new DividerItemDecoration(getContext(), DividerItemDecoration.VERTICAL);
        itemDecoration.setDrawable(ContextCompat.getDrawable(getContext(), R.drawable.custom_divider));
        mSwipeMenuRecyclerView.addItemDecoration(itemDecoration);
        mSwipeMenuRecyclerView.setAdapter(mAdapter);
    }

    @Override
    protected void initData() {
        mRefreshLayout.setOnRefreshListener(refreshLayout -> refreshData()).setOnLoadMoreListener(refreshLayout -> mPresenter.getCollectionList(pageIndex));
        mRefreshLayout.autoRefresh();
    }

    private void refreshData() {
        pageIndex = 0;
        mList.clear();
        mPresenter.getCollectionList(pageIndex);
    }

    @OnClick(R.id.ll_goto_car)
    void ll_goto_car() {
        startActivity(new Intent(this, ShoppingCartActivity.class));
    }

    @Override
    protected MyCollectionPresenter createPresenter() {
        return new MyCollectionPresenter();
    }

    @Override
    public void showLoadingView() {
        showLoadingDialog();
    }

    @Override
    public void hideLoadingView() {
        hideLoadingDialog();
    }

    @Override
    public void onNetworkError() {
        mRefreshLayout.finishRefresh().finishLoadMore();
    }

    @Override
    public void showCollectionList(HttpRespond<String> respond) {
        mRefreshLayout.finishRefresh().finishLoadMore();
        if (respond.result == 1) {
            if (respond.isaes == 1) {
                LogUtil.e("我的收藏数据:" + SafeUtils.decrypt(respond.data));
                List<CollectionBean> list = new Gson().fromJson(SafeUtils.decrypt(respond.data), new TypeToken<List<CollectionBean>>() {
                }.getType());
                if (list.size() > 0) {
                    pageIndex++;
                }
                mList.addAll(list);
            }
        } else
            ToastHelper.getInstance(this).showWarn(respond.message);
        mAdapter.notifyDataSetChanged();
    }

    @Override
    public void showDesCollection(HttpRespond<String> respond) {
        ToastHelper.getInstance(this).showSucceed(respond.message);
        if (respond.result == 1) {
            refreshData();
        }
    }

    @Override
    public void showAddToCarRes(HttpRespond<AddToCarBean> respond) {
        sendToUpdateCarNum();
        mPresenter.getCarNum();
        if (respond.result == 1) {
            //修改数量
            mList.get(fatherPos).getSkuList().get(childPos).setNum(Integer.parseInt(respond.data.getQuantity()));
            mSpecificationAdapter.notifyItemChanged(childPos);

            if (mShowAnim)
                mAnimUtils.startAnim(mClickItemView, mEndView);
        } else
            ToastHelper.getInstance(this).showWarn(respond.message);
    }

    @Override
    public void showCarNum(HttpRespond<ShoppingCarBean> response) {
        if (response.result == 1) {
            ShoppingCarBean bean = response.data;
            tv_num.setVisibility(bean.getNum() == 0 ? View.GONE : View.VISIBLE);
            tv_num.setText(String.format("共%d种，%s元", bean.getNum(), bean.getPrice()));
        }
    }

    @Override
    public void onResume() {
        super.onResume();
        mPresenter.getCarNum();
    }

    /**
     * 发送广播通知刷新购物车数量
     */
    private void sendToUpdateCarNum() {
        EventBus.getDefault().post(new RefreshEvent());
    }

    /**
     * 创建侧滑删除
     *
     * @param swipeLeftMenu
     * @param swipeRightMenu
     * @param viewType
     */
    @Override
    public void onCreateMenu(SwipeMenu swipeLeftMenu, SwipeMenu swipeRightMenu, int viewType) {
        int width = (int) getResources().getDimension(R.dimen.dp_70);
        int height = ViewGroup.LayoutParams.MATCH_PARENT;

        SwipeMenuItem deleteItem = new SwipeMenuItem(this)
                .setBackgroundColor(Color.parseColor("#83c120"))
                .setText("删除")
                .setTextSize(18)
                .setTextColor(Color.WHITE)
                .setWidth(width)
                .setHeight(height);
        swipeRightMenu.addMenuItem(deleteItem);
    }

    /**
     * 删除事件
     *
     * @param menuBridge
     */
    @Override
    public void onItemClick(SwipeMenuBridge menuBridge) {
        menuBridge.closeMenu();
        int position = menuBridge.getAdapterPosition();
        if (menuBridge.getDirection() == SwipeMenuRecyclerView.RIGHT_DIRECTION) {
            //删除
            mPresenter.delCollection(mList.get(position).getID());
        }
    }

    private SpecificationAdapter mSpecificationAdapter;
    private int childPos;
    private int fatherPos;

    class CollectionAdapter extends RecyclerView.Adapter<CollectionAdapter.Holder> {
        @NonNull
        @Override
        public CollectionAdapter.Holder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
            Holder holder = new Holder(getLayoutInflater().inflate(R.layout.item_collection, parent, false));
            holder.itemView.setOnClickListener(v -> GoodsDetailsActivity.start(MyCollectionActivity.this, mList.get(holder.getAdapterPosition()).getID()));
            /*holder.ivCollect.setOnClickListener(v -> {
                if (Global.checkLogin(MyCollectionActivity.this)) {
                    collectOperatePosition = holder.getAdapterPosition();
                    GoodsBean2 goodsBean = mList.get(holder.getAdapterPosition());
                    getPresenter().collectionGoods(goodsBean.getID(), Math.abs(goodsBean.getIsCollection() - 1));
                }
            });*/
            return holder;
        }

        @Override
        public void onBindViewHolder(@NonNull CollectionAdapter.Holder holder, int position) {
            CollectionBean goods = mList.get(position);
            ImageUtils.getInstance().showImage( goods.getDeputyPic(), holder.ivCover);
            holder.tvTitle.setText(goods.getName());
            holder.tvDesc.setText(goods.getDes());
            holder.tvOriginMoney.setText(String.format("￥%s元", goods.getMarketPrice()));
            holder.tvOriginMoney.setPaintFlags(Paint.STRIKE_THRU_TEXT_FLAG);
            holder.tvPrice.setText(String.format("￥%s元", goods.getUnitPrice()));
            holder.tvUnit.setText(String.format("/%s", goods.getPriceName()));
            //是否为新品
            if (goods.getIsNew() == 1) {
                holder.flIsNew.setVisibility(View.VISIBLE);
            } else {
                holder.flIsNew.setVisibility(View.GONE);
            }
//            holder.ivCollect.setImageResource(goods.getIsCollection() == 1 ? R.mipmap.ic_goods_collected : R.mipmap.ic_goods_collect);

            holder.mRvSpecification.setVisibility(goods.isOpen ? View.VISIBLE : View.GONE);

            holder.mRvSpecification.setLayoutManager(new LinearLayoutManager(getContext()));
            mSpecificationAdapter = new SpecificationAdapter(goods.getSkuList(), holder);
            holder.mRvSpecification.setAdapter(mSpecificationAdapter);
            holder.ivAddCart.setOnClickListener(v -> {
                if (Global.checkLogin(getContext())) {
                    goods.isOpen = !goods.isOpen;
                    holder.mRvSpecification.setVisibility(goods.isOpen ? View.VISIBLE : View.GONE);
                    new Handler().postDelayed(() -> {
                        if (mLayoutManager.findLastVisibleItemPosition() == holder.getAdapterPosition()
                                && holder.mRvSpecification.getVisibility() == View.VISIBLE) {
                            mSwipeMenuRecyclerView.smoothScrollBy(0, holder.mRvSpecification.getHeight());
                        }
                    }, 40);
                }
            });
        }

        @Override
        public int getItemCount() {
            return mList.size();
        }

        public class Holder extends RecyclerView.ViewHolder {
            @BindView(R.id.fl_is_new)
            FrameLayout flIsNew;
            @BindView(R.id.tv_title)
            TextView tvTitle;
            @BindView(R.id.tv_desc)
            TextView tvDesc;
            @BindView(R.id.tv_price)
            TextView tvPrice;
            @BindView(R.id.tv_origin_money)
            TextView tvOriginMoney;
            @BindView(R.id.tv_unit)
            TextView tvUnit;
            @BindView(R.id.iv_cover)
            ImageView ivCover;
            @BindView(R.id.iv_add_cart)
            ImageView ivAddCart;
            @BindView(R.id.iv_collect)
            ImageView ivCollect;

            @BindView(R.id.mRvSpecification)
            RecyclerView mRvSpecification;

            public Holder(View itemView) {
                super(itemView);
                ButterKnife.bind(this, itemView);
            }
        }
    }

    public class SpecificationAdapter extends RecyclerView.Adapter<SpecificationAdapter.Holder> {

        private List<CollectionBean.SkuListBean> skuList;
        private CollectionAdapter.Holder mHolder;

        public SpecificationAdapter(List<CollectionBean.SkuListBean> skuList, CollectionAdapter.Holder holder) {
            this.skuList = skuList;
            this.mHolder = holder;
        }

        @NonNull
        @Override
        public Holder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
            return new Holder(LayoutInflater.from(getContext()).inflate(R.layout.item_add_to_cart_category, parent, false));
        }

        @Override
        public void onBindViewHolder(@NonNull Holder holder, int position) {

            CollectionBean.SkuListBean bean = skuList.get(position);
            holder.item_price.setText(String.format("￥%s", bean.getPrice()));
            holder.item_specification.setText(String.format("/(%s%s/%s)", bean.getQuantity(), bean.getComSp(), bean.getSkuSp()));
            holder.item_unit_price.setText(String.format("每%s￥%s元", bean.getComSp(), bean.getUnitPrice()));
            holder.edt_num.setText(bean.getNum() + "");

            holder.edt_num.addTextChangedListener(new TextWatcher() {
                @Override
                public void beforeTextChanged(CharSequence s, int start, int count, int after) {

                }

                @Override
                public void onTextChanged(CharSequence s, int start, int before, int count) {

                }

                @Override
                public void afterTextChanged(Editable s) {
                    if (s.length() == 0) {
                        holder.edt_num.setText("0");
                        holder.edt_num.setSelection(0,1);
                    }
                }
            });

            holder.edt_num.setOnFocusChangeListener((v, hasFocus) -> {
                LogUtil.e(position + "," + bean.getSkuId() + "," + hasFocus);
                if (!hasFocus) {
                    fatherPos = mHolder.getAdapterPosition();
                    childPos = position;
                    mPresenter.addToCar(bean.getSkuId(), holder.edt_num.getText().toString());
                    mClickItemView = mHolder.ivCover;
                    mShowAnim = true;
                }
            });

            holder.itemView.setOnClickListener(v -> holder.itemView.setFocusable(true));

            holder.plus.setOnClickListener(v -> {
                fatherPos = mHolder.getAdapterPosition();
                childPos = position;
                LogUtil.e("加--" + fatherPos + "," + childPos);
                holder.edt_num.setText(Integer.parseInt(holder.edt_num.getText().toString()) + 1 + "");
                mPresenter.addToCar(bean.getSkuId(), holder.edt_num.getText().toString());
                mClickItemView = mHolder.ivCover;
                mShowAnim = true;
            });

            holder.reduce.setOnClickListener(v -> {
                fatherPos = mHolder.getAdapterPosition();
                childPos = position;
                LogUtil.e("减--" + fatherPos + "," + childPos);
                holder.edt_num.setText(Integer.parseInt(holder.edt_num.getText().toString()) - 1 < 0 ? "0" : Integer.parseInt(holder.edt_num.getText().toString()) - 1 + "");
                mPresenter.addToCar(bean.getSkuId(), holder.edt_num.getText().toString());
                mShowAnim = false;
            });
        }

        @Override
        public int getItemCount() {
            return skuList == null ? 0 : skuList.size();
        }

        public class Holder extends RecyclerView.ViewHolder {
            @BindView(R.id.item_price)
            TextView item_price;
            @BindView(R.id.item_specification)
            TextView item_specification;
            @BindView(R.id.item_unit_price)
            TextView item_unit_price;
            @BindView(R.id.iv_plus)
            ImageView plus;
            @BindView(R.id.iv_reduce)
            ImageView reduce;
            @BindView(R.id.tv_num)
            EditText edt_num;

            public Holder(View itemView) {
                super(itemView);
                ButterKnife.bind(this, itemView);
            }
        }
    }
}
